<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="500"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        @ok="onSubmit"
        @cancel="handleCancle"
    >
        <a-form
            layout="horizontal"
            :model="formState"
            :rules="rules"
            ref="formRef"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
        >
            <a-form-item
                :label="t('yl.tmpModelFormLabel')"
                name="relationTemplateCode"
                style="border-bottom: 1px solid #ccc; padding-bottom: 20px"
            >
                <a-select
                    v-model:value="formState.relationTemplateCode"
                    @change="selectChange(formState.relationTemplateCode, 0)"
                >
                    <a-select-option
                        :disabled="getDisable(item.templateCode)"
                        :value="item.templateCode"
                        v-for="(item, index) in formState.templateList"
                        :key="index"
                        >{{ item.templateName }}</a-select-option
                    >
                </a-select>
            </a-form-item>
            <block v-if="tagColourName == '全彩'">
                <a-form-item :label="t('yl.tmpCombinationLabel')">
                    <a-input disabled v-model:value="formState.templateName" />
                </a-form-item>
                <a-row v-for="(item, index) in formState.templateCodes" :key="index">
                    <a-col :span="24">
                        <a-form-item
                            label=" "
                            class="tmpLabel"
                            :name="['templateCodes', index, 'templateCode']"
                            :rules="{
                                required: true,
                                message: t('yl.tmpModelFormTips'),
                                trigger: 'change',
                            }"
                        >
                            <a-select v-model:value="item.templateCode" @change="selectChange(item.templateCode, index + 1)">
                                <a-select-option
                                    :value="item.templateCode"
                                    v-for="(item, index) in formState.templateList"
                                    :disabled="getDisable(item.templateCode)"
                                    :key="index"
                                    >{{ item.templateName }}</a-select-option
                                >
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
            </block>
        </a-form>
        <div style="width: 100%; text-align: right" v-if="tagColourName == '全彩'">
            <a-button
                type="primary"
                danger
                @click="addTemplateCode"
                v-if="formState.templateCodes.length != formState.templateList.length"
            >
                新增</a-button
            >
            <a-button
                type="primary"
                style="margin-left: 10px"
                danger
                @click="delTemplateCode"
                v-if="formState.templateCodes.length !== 1"
            >
                删除</a-button
            >
        </div>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { PaginationQuery } from '@/types/table';
import useRoles from '@/hooks/useRoles';
import useDepts from '@/hooks/useDepts';
import { validators } from '@/utils';
import { UserInfo } from '@/types/user';
import { getSimilarTemplate, putRelevanceTemplate } from '@/api/templates';
import ylTreeselectVue from '@/components/ylTreeselect.vue';
import { delay } from 'lodash';

// 表单校验规则
const initRules = (t: fn) => {
    return {
        relationTemplateCode: [{ required: true, message: t('yl.pleaseInputUsername'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'userModel',
    components: {
        ylTreeselectVue,
    },
    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },
        title: {
            type: String,
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        templateCode: {
            type: String,
            default: () => '',
        },
        templateName: {
            type: String,
            default: () => '',
        },
        relationTemplateCode: {
            type: String,
            default: () => '',
        },
        templateList: {
            type: Array,
            default: () => [],
        },
        tagColourName: {
            type: String,
            default: () => '',
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        console.log(props);
        const { t } = useI18n();
        const showModal = computed(() => props.visible);
        const formState = reactive({
            relationTemplateCode: props.relationTemplateCode,
            templateCode: props.templateCode,
            templateCodes: [{ templateCode: '' }],
            templateList: [],
            templateName: props.templateName,
        });
        const selectedOptions = ref([]);
        const tagColourName = props.tagColourName;
        onMounted(() => {
            console.log(formState);
            if (props.relationTemplateCode) {
                formState.templateList.push(formState.relationTemplateCode);
                selectChange(formState.relationTemplateCode, 0);
                if (props.templateList.length) {
                    formState.templateCodes = [];
                    for (let i = 0; i < props.templateList.length; i++) {
                        formState.templateList.push(props.templateList[i].templateCode);
                        formState.templateCodes.push({ templateCode: props.templateList[i].templateCode });
                        selectChange(props.templateList[i].templateCode, i + 1);
                    }
                }
            }
            SimilarTemplate();
        });

        // 表单校验
        const rules = initRules(t);
        const formRef = ref();

        // 提交
        const onSubmit = () => {
            console.log(formState);

            formRef.value.validate().then(() => {
                let list: any = [];

                formState.templateCodes.forEach((i) => {
                    if (i.templateCode) {
                        list.push(i.templateCode);
                    }
                });
                let data = {
                    relationTemplateCode: formState.relationTemplateCode,
                    templateCode: formState.templateCode,
                    templateCodes: list,
                };
                console.log(data);
                putRelevanceTemplate(data).then((res) => {
                    console.log(res);
                    const timer = setTimeout(() => {
                        emit('submit', 'submit');
                        clearTimeout(timer);
                    }, 500);
                });
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('submit', 'cancle');
        };

        const SimilarTemplate = () => {
            getSimilarTemplate(1, formState.templateCode).then((res) => {
                console.log(res);
                formState.templateList = res.content;
                console.log(formState.templateList);
            });
            // let data = getSimilarTemplate(1, formState.templateCode);

            // templateList = content;
        };
        const getDisable = (value) => {
            if (selectedOptions.value.indexOf(value) >= 0) {
                return true;
            } else {
                return false;
            }
        };
        const selectChange = (value: any, index: number) => {
            console.log(arguments);
            console.log(value, index);
            selectedOptions.value[index] = value;
        };
        const addTemplateCode = () => {
            if (formState.templateCodes.length >= formState.templateList.length) {
                return;
            }
            formState.templateCodes.push({ templateCode: '' });
        };
        return {
            formRef,
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
            showModal,
            formState,
            t,
            rules,
            onSubmit,
            handleCancle,

            SimilarTemplate,
            getDisable,
            selectChange,
            selectedOptions,
            addTemplateCode,
            tagColourName,
        };
    },
});
</script>
<style lang="scss">
.tmpLabel {
    .ant-form-item-label > label::after {
        content: '' !important;
        position: relative;
        top: -0.5px;
        margin: 0 8px 0 2px;
    }
}
</style>
